<template>
  <div class="base-header-container">
    <div>
      <div>
        <img
          :src="isCollapse ? collapseLogoUrl : logoUrl"
          :class="isCollapse ? 'small-logo' : 'normal-logo'"
          alt="logo"
        />
        <span class="ft-size20">
          <menu-fold-outlined
            v-if="!isCollapse"
            @click="toogleCollapse(true)"
          />
          <menu-unfold-outlined v-else @click="toogleCollapse(false)" />
        </span>
        <span class="refresh" @click="refreshPage">
          <redo-outlined />
        </span>
        <div class="operate-container">
          <a-dropdown
            trigger="click"
            v-model:visible="dropVisible"
            v-if="!isEnvOnline"
          >
            <span class="current-line-container mr-3" @click="onCurrentDrop">
              <span class="line-info mr-5">
                <span class="mr-3">
                  <check-circle-filled :style="{ color: '#4DF5D7', fontSize: '14px' }"  v-if="currentLine.status" />
                  <minus-circle-filled :style="{ color: '#BCBCBC', fontSize: '14px' }" v-else />
                </span>
                <span v-if="currentLine" :title="currentLine.name" >{{ currentLine.name }}({{ currentLine.lineNo }})</span >
              </span>
              <span class="line-info-arrow"> 
                <up-outlined v-if="dropVisible" />
                <down-outlined v-else />
              </span>
            </span>
            <template #overlay>
              <a-menu v-if="hangerLineList.length" class="header-line-menu">
                <a-menu-item
                  divided
                  v-for="item in hangerLineList"
                  :key="item.id"
                  @click="changeLine(item.id, item.name, item)"
                >
                  <span
                    :class="[item.status ? 'text-success' : 'text-gray', 'mr-5']"
                  >
                    <check-circle-filled v-if="item.status" />
                    <minus-circle-filled v-else />
                  </span>
                  {{ item.name }}
                </a-menu-item>
              </a-menu>
              <!-- <div v-else>暂时无线</div> -->
            </template>
          </a-dropdown> 
          <a-switch @click="changeLineStatus" :checked="currentLineStatus" v-if="!isEnvOnline" class="mr-8">
            <template #checkedChildren><check-outlined /></template>
            <template #unCheckedChildren><close-outlined /></template>
          </a-switch>
          <span class="operate-container-more"  @click="changeLineStatusMore" v-if="!isEnvOnline" style="overflow: hidden;">{{ $t('hangManage.more') }}</span>
        </div>
          
        <a-divider type="vertical" v-if="!isEnvOnline" />
      </div>
      <header-menu></header-menu>
    </div>
    <div>
      <LockPage />
      <BookMarks />
      <span class="mr-25"></span>
      <HeaderNotice v-if="!isEnvOnline" />
      <TvScreen />
      <a-avatar :alt="userInfo.userName" :src="userInfo.avatar" style="margin-right: 8px">{{
        !userInfo.avatar && userInfo.userName
      }}</a-avatar>
      <a-dropdown>
        <span class="current-user-container">
          <span class="user-name" :title="userInfo.userName"
            >{{ userInfo.userName }}</span
          >
          <DownOutlined class="ft-size12 down-arrow" />
        </span>
        <template #overlay>
          <a-menu>
            <a-menu-item divided @click="editPwd">{{$t('layout.editPwd')}}</a-menu-item>
            <a-sub-menu key="sub1" :title="$t('layout.languageManage')">
              <!-- class="border-bottom" -->
              <a-menu-item
                divided
                v-for="item in langList"
                :key="item.value"
                @click="changeLang(item.value, item.text)"
              >
                {{ item.text }}
              </a-menu-item>
            </a-sub-menu>
            <a-divider class="m-0 mx-12" />
            <a-menu-item divided @click="logout">{{$t('layout.loginOut')}}</a-menu-item>
          </a-menu>
        </template>
      </a-dropdown>
    </div>
    <edit-pwd-modal ref="editPwdModal" />
    <CustomModal ref="customModalRef" @ok="onOk" :needCloseInner="false" />
    <EditOtherModal
      ref="editOtherModalRef"
      @ok="modalDesignMore"
      @cancel="modalDesignMoreCancel"
    ></EditOtherModal>
  </div>
</template>

<script>
import { store } from "@/store"
import { mapState } from "vuex"
import EditPwdModal from "./editPwdModal.vue"
import CustomModal from "@/components/confirmModal/customModal.vue"
import HeaderNotice from "./headerNotice.vue"
import LockPage from "./lockPage.vue"
import TvScreen from "./tvScreen.vue"
import BookMarks from './bookMarks.vue'
import {
  MenuFoldOutlined,
  MenuUnfoldOutlined,
  DownOutlined,
  RedoOutlined, 
  UpOutlined,
  CheckCircleFilled,
  MinusCircleFilled,
  CheckOutlined,
  CloseOutlined
} from "@ant-design/icons-vue";
import HeaderMenu from "./headerMenu.vue";
import axios from "@/utils/request";
// import { clearLocalStorage, getLocalStorage } from "@/utils";
import { clearSpecifiedLocalStorage, getLocalStorage } from "@/utils";
import EditOtherModal from "@/views/hangManage/prodTimeInfo/modules/editOtherModal.vue";
export default {
  data() {
    return {
      logoUrl: require(process.env.VUE_APP_HEAD_LOGO),
      collapseLogoUrl: require(process.env.VUE_APP_HEAD_LITTLE_LOGO),
      collapseEnLogoUrl: require(process.env.VUE_APP_HEAD_LITTLE_EN_LOGO),
      langList: [
        { text: this.$t('layout.chinese'), value: "zh-cn" },
        { text: this.$t('layout.english'), value: "en_US" },
        { text: this.$t('layout.kzc'), value: "km_KH" },
        { text: this.$t('layout.vivn'), value: 'vi_VN' },
        { text: this.$t('layout.eses'), value: 'es_ES' },
      ],
      text: this.$t('layout.chinese'),
      userInfo: {},
      hangerLineList: [],
      currentLine: {},
      currentLineStatus: true,
      dropVisible: false,
      userVisible: false,
      isEnvOnline: process.env.VUE_APP_CONFIG == "online",
    };
  },
  components: {
    HeaderMenu,
    MenuFoldOutlined,
    MenuUnfoldOutlined,
    DownOutlined,
    RedoOutlined, 
    EditPwdModal,
    UpOutlined,
    CustomModal,
    CheckCircleFilled,
    MinusCircleFilled,
    HeaderNotice,
    LockPage,
    TvScreen,
    EditOtherModal,
    BookMarks,
    CheckOutlined,
    CloseOutlined
  },
  computed: {
    ...mapState({
      isCollapse: (state) => state.setting.isCollapse,
      operateNoticeList: (state) => state.operateData.operateNoticeList,
    }),
  },
  methods: {
    refreshPage() {
      store.commit("updateState", { isShowView: false });
      this.$nextTick(() => {
        store.commit("updateState", { isShowView: true });
      });
    },
    toogleCollapse(value) {
      localStorage.setItem("isCollapse", JSON.stringify(value));
      store.commit("updateState", { isCollapse: value });
    },
    changeLang(value, name) {
      this.text = name;
      localStorage.setItem("locale", value);
      store.commit("updateState", { lang: value });
      // this.refreshPage();
      location.reload()
    },
    changeLine(value, name, item) {
      this.dropVisible = false;
      this.currentLine = item;
      this.currentLineStatus = item.status;
      localStorage.setItem("currentLine", JSON.stringify(item));
      localStorage.setItem(
        "currentLineStatus",
        JSON.stringify(this.currentLineStatus)
      );
      store.commit("updateState", { currentLine: this.currentLine });
    },
    async logout() {
      const res = await axios.postAction("/api/logout", {});
      if (res.success) {
        // clearLocalStorage();
        clearSpecifiedLocalStorage();
        this.$router.push("/login");
        store.commit("updateState", {
          tabs: [],
          activeFirstMenu: null,
          activeFirstMenuName: null,
          subMenu: [],
          activeSideMenu: "",
        });
      }
    },
    editPwd() {
      this.$refs.editPwdModal.open();
    },
    changeLineStatusMore() {
      this.$refs.editOtherModalRef.open();
    },
    // 批量启动弹框确定
    modalDesignMore() {
      this.currentLine.status = getLocalStorage("currentLineStatus");
      this.currentLineStatus = getLocalStorage("currentLineStatus");
    },
    // 批量启动弹框关闭
    modalDesignMoreCancel() {},
    async changeLineStatus() {
      if (!this.currentLine) {
        this.$message.warning(this.$t('video.pleaseSelectWaterLine'));
        return;
      }
      let opts = {
        content: this.currentLineStatus
          ? `${this.$t('layout.trueClose')}<b>${this.currentLine.name}</b>${this.$t('sysManage.what')}？`
          : `${this.$t('layout.trueStart')}<b>${this.currentLine.name}</b>${this.$t('sysManage.what')}？`,
        btnText: this.currentLineStatus ? this.$t('layout.close') : this.$t('layout.start'),
      };
      this.$refs.customModalRef.open(opts);
    },
    async onOk() {
      let url = this.currentLineStatus
        ? "/api/device/line-control/stop"
        : "/api/device/line-control/run";
      try {
        const res = await axios.postAction(url, [
          {
            line: this.currentLine.lineNo,
            startUp: this.currentLineStatus ? 0 : 1,
          },
        ]);
        if (res.success) {
          this.$message.success(
            res.msg || (this.currentLineStatus ? this.$t('layout.closeTrue') : this.$t('layout.startTrue'))
          );
          // 之后根据状态更改
          this.currentLine.status = !this.currentLineStatus;
          this.currentLineStatus = !this.currentLineStatus;
          localStorage.setItem(
            "currentLineStatus",
            JSON.stringify(this.currentLineStatus)
          );
        } else {
          this.$message.warning(res.msg || this.$t('common.errorTip'));
        }
        this.$refs.customModalRef.visible = false;
      } catch {
        this.$refs.customModalRef.visible = false;
      }
    },
    async onCurrentDrop() {
      if (!this.dropVisible) {
        await this.getLineListStatus();
        this.dropVisible = true;
      } else {
        this.dropVisible = false;
      }
    },
    async getLineListStatus() {
      try {
        let lineNos = this.hangerLineList.map((i) => i.lineNo);
        const res = await axios.postAction(
          "/api/hanger/hangerline-realtime/get-line-status",
          lineNos
        );
        if (res.success && res.data) {
          this.hangerLineList = res.data;
          localStorage.setItem(
            "hangerLineList",
            JSON.stringify(this.hangerLineList)
          );
        }
      } catch {
        console.log("_______");
      }
    },
  },
  created() {
    // let locale = localStorage.getItem('locale')
    // if (locale == 'en'){
    //   this.logoUrl = this.collapseEnLogoUrl
    // }
    // this.userInfo = getLocalStorage("user") || {};
    // this.hangerLineList = getLocalStorage("hangerLineList") || [];
    // this.currentLine = getLocalStorage("currentLine");
    // this.currentLineStatus = getLocalStorage("currentLineStatus");
    // store.commit("updateState", { currentLine: this.currentLine });
    // store.dispatch("getUntreatNotice");
  },
};
</script>